package cn.bupt.adt.interceptor;

import cn.bupt.adt.constant.Constants;
import cn.bupt.adt.entity.autogenerate.AdminUser;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>Title:LogInterceptor后台登陆验证拦截器</p>
 * <p>Description:</p>
 *
 * @author waiting
 * @date 2016年7月14日 下午3:16:20
 */
@Component
public class LogInterceptor extends HandlerInterceptorAdapter {

    private AdminUser users;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath() + "/";
        String url = requestUri.substring(contextPath.length());
        if (url.equals(Constants.PUBLIC_LOGIN)) {
            return true;
        }
        HttpSession session = request.getSession();
        users = (AdminUser) session.getAttribute(Constants.ADMIN_USER);
        if (null == users || !request.getRemoteAddr().equals(session.getAttribute(Constants.LAST_LOGIN_IN_IP))) {
            java.io.PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<script>");
            String path = request.getContextPath() + "/" + Constants.PUBLIC_LOGIN;
            out.println("window.open('" + path + "','_top')");
            out.println("</script>");
            out.println("</html>");
            System.out.println(request.getHeader("Referer") + "被拦截了，没有请求到");
            return false;
        }
        return true;
    }

}
